package com.deep.common;

import com.alibaba.fastjson.JSONObject;
import com.deep.bean.TransformConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.shaded.jackson2.org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ProfileConfig {

    public static TransformConfig getTransformConfig(String profile)  {
        String profilePath = String.format("application-%s.yml", profile);

        JSONObject configJson = readJson(profilePath);
        log.info("configJson = {}", configJson);
        TransformConfig config = configJson.toJavaObject(TransformConfig.class);
        log.info("config = {}", config);

        return config;
    }

    public static JSONObject parseConfig(String profile)  {
        String profilePath = String.format("application-%s.yml", profile);

        JSONObject configJson = readJson(profilePath);
        log.info("configJson = {}", configJson);

        return configJson;
    }

    public static JSONObject readJson(String fileName) {
        JSONObject jsonObject = new JSONObject(readYml(fileName));
        return jsonObject;
    }

    public static Map<String, Object> readYml(String fileName) {
        Map<String, Object> data = new HashMap<>();
        try {
            // 文件名前面不能加斜杆
            // 也可以使用 Loader.class.getClassLoader().getResourceAsStream

            // 加载YML文件
            InputStream inputStream = ProfileConfig.class.getClassLoader().getResourceAsStream(fileName);
            assert inputStream != null;

            // 防止出现中文乱码
            // BufferedReader bf = new BufferedReader(new InputStreamReader(in));


            Yaml yaml = new Yaml();

            // 解析YML数据
             data = yaml.load(inputStream);

            // 打印YML数据
            System.out.println(data);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
}
